﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Arch.Model;

namespace Arch.Common.Validation
{
    public static class ValidationExtentions
    {
        public static void Validate(this object obj)
        {
            var validationContext = new ValidationContext(obj, null, null);
            var validationResults = new List<ValidationResult>();
            Validator.TryValidateObject(obj, validationContext, validationResults, true);
            var errors = validationResults;

            if (errors.Count() > 0)
            {
                if (obj is IValidationErrorInfo)
                {
                    var modelWithInfos = obj as IValidationErrorInfo;

                    foreach (var error in errors)
                    {
                        modelWithInfos.AddError(error);
                    }

                }
                throw new ValidationException(errors.First().ErrorMessage);
            }
        }
    }
}
